﻿namespace CN2P.ServiceModel.ServiceClients {
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Text;

    public class OrdersServiceClient : BaseServiceClient
    {
        public OrdersServiceClient(string baseUrl)
            : base(baseUrl) {
        }

        public IList<OrderModel> GetUserOrders(string userId)
        {
            var url = this.GetOrdersUrl(userId);
            var response = this.ExecuteGet<IList<OrderModel>>(url);
            this.ValidateResponse(response, HttpStatusCode.OK);
            var model = response.Content;
            return model;
        }

        public OrderModel GetUserOrder(string userId, string orderId)
        {
            var url = this.GetOrderUrl(userId, orderId);
            var response = this.ExecuteGet<OrderModel>(url);
            this.ValidateResponse(response, HttpStatusCode.OK);
            var model = response.Content;
            return model;
        }

        public void DeleteAll() {
            var url = GetOrdersUrl();
            var response = this.ExecuteDelete(url);
            this.ValidateResponse(response, HttpStatusCode.Created);
        }

        protected string GetOrderUrl(string userId, string orderId)
        {
            return this.GetOrdersUrl(userId) + orderId;
        }

        protected string GetOrdersUrl(string userId)
        {
            var bytes = Encoding.UTF8.GetBytes(userId);
            var base64 = Convert.ToBase64String(bytes);
            var encoded = Uri.EscapeUriString(base64);
            return this.GetOrdersUrl() + encoded + "/";
        }

        protected string GetOrdersUrl()
        {
            return _baseUrl + "api/orders/";
        }
    }
}
